import { asyncRouterMap, constantRouterMap } from '@/router'
// import Layout from "../../views/layout/Layout";
const _import = require('../../router/_import')

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        let routerList = data.myRouters
        let myRouters = asyncRouterMap
        for (let i = 0; i < routerList.length-1; i++) {
          let routerInfo = routerList[i]
          let menuInfo = {
            path: routerInfo.path,
            component: _import(routerInfo.component),
          }
          // 开始装配Children
          let routerInfoChilden = routerInfo.children;
          let menuChildren = []
          for (let j = 0; j < routerInfoChilden.length; j++){
            let childenMeta = {
              icon: routerInfoChilden[j].meta.icon,
              title: routerInfoChilden[j].meta.title
            }
            if (routerInfoChilden[j].meta.noCache) {
              childenMeta.noCache = true
            }
            menuChildren.push({
              path: routerInfoChilden[j].path,
              name: routerInfoChilden[j].name,
              component: _import('backstage/' + routerInfoChilden[j].component),
              meta: childenMeta
            })
          }
          menuInfo.children = menuChildren
          // 结束装配Children
          if (routerInfo.meta) {
            //一级菜单有子菜单
            menuInfo.redirect = routerInfo.redirect
            menuInfo.name = routerInfo.name
            menuInfo.meta = routerInfo.meta
          }
          myRouters.push(menuInfo)
        }
        myRouters.push({
          path: routerList[routerList.length-1].path,
          redirect: routerList[routerList.length-1].redirect,
          hidden: true
        })
        commit('SET_ROUTERS', myRouters)
        resolve()
      })
    }
  }
}

export default permission
